//
//  StarSlider.m
//  兔管家
//
//  Created by 123 on 15/11/4.
//  Copyright © 2015年 RK. All rights reserved.
//

#import "StarSlider.h"
#define OFF_ART	[UIImage imageNamed:@"star_bai"]
#define ON_ART	[UIImage imageNamed:@"star_huang"]
#define IMAGEWIDTH 50

@implementation StarSlider

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        for (int count = 0; count<5; count++) {
            UIImageView *starView = [[UIImageView alloc]initWithFrame:CGRectMake(35*count, 0, 30, 30)];
            starView.image = OFF_ART;
            [self addSubview:starView];
        }
    }
    return self;
}
//返回控件内置大小
- (CGSize)intrinsicContentSize
{
    return CGSizeMake(170, 30);
}
- (void)updateValueAtPoint:(CGPoint)point
{
    NSUInteger newValue = 0;
    UIImageView *changeStarView = nil;
    for (UIImageView *starView in self.subviews) {
        if (point.x < starView.frame.origin.x) {
            starView.image = OFF_ART;
        }else{
            starView.image = ON_ART;
            changeStarView = starView;
            newValue++;
        }
    }
    if (self.value!=newValue) {
        if (self.valueBlock) {
            self.valueBlock(newValue);
        }
        self.value = newValue;
        [self sendActionsForControlEvents:UIControlEventValueChanged];
        [UIView animateWithDuration:0.15f animations:^{
            changeStarView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
        } completion:^(BOOL finished) {
            changeStarView.transform = CGAffineTransformIdentity;
        }];
    }
}
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    [self updateValueAtPoint:[touch locationInView:self]];
    return YES;
}
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchPoint = [touch locationInView:self];
    if (CGRectContainsPoint(self.frame, touchPoint))
        [self sendActionsForControlEvents:UIControlEventTouchDragInside];
    else
        [self sendActionsForControlEvents:UIControlEventTouchDragOutside];
    [self updateValueAtPoint:[touch locationInView:self]];
    return YES;
}
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchPoint = [touch locationInView:self];
    if (CGRectContainsPoint(self.bounds, touchPoint))
        [self sendActionsForControlEvents:UIControlEventTouchUpInside];
    else
        [self sendActionsForControlEvents:UIControlEventTouchUpOutside];
}
- (void)cancelTrackingWithEvent:(UIEvent *)event
{
    [self sendActionsForControlEvents:UIControlEventTouchCancel];
}
- (void)setValue:(NSUInteger)value
{
    _value = value;
    NSArray *starArray = self.subviews;
    UIImageView *starView = nil;
    for (int count = 0; count<value; count++) {
        starView = starArray[count];
        starView.image = ON_ART;
    }
}
@end
